<template>
  <div>
    <a-drawer
      title="重新发送"
      :visible="visible"
      :destroyOnClose="true"
      :width="800"
      :body-style="{ paddingBottom: '80px' }"
      @close="closeDrawer"
    >
      <a-form layout="vertical">
        <a-row :gutter="12" style="margin-top: 20px">
          <a-col :span="24">
            <a-form-item
              label="通知方式:"
              v-bind="validateInfos.checkedNoticeList"
            >
              <a-checkbox
                v-model:checked="noticeAll"
                :indeterminate="indeterminate"
                @change="onNoticeAllChange"
              >
                全选
              </a-checkbox>
              <a-checkbox-group v-model:value="modelRef.checkedNoticeList">
                <a-checkbox
                  v-for="item in noticeTypeList"
                  :key="item.key"
                  :value="item.key"
                  >{{ item.name }}</a-checkbox
                >
              </a-checkbox-group>
            </a-form-item>
          </a-col>
        </a-row>
        <a-alert
          showIcon
          message="如无通知单接收人请新建，无接收人或接收人信息不完善将无法进行发送。"
          type="info"
          style="margin-top: 10px; margin-bottom: 10px"
        />
        <a-form-item v-bind="validateInfos.receiverList">
          <a-table
            :columns="contactColumns"
            :data-source="contactList"
            :loading="contactListLoading"
            :pagination="contactPagination"
            rowKey="id"
            :row-selection="{
              selectedRowKeys: selectedRowKeys,
              onChange: onSelectChange,
            }"
            @change="handleTableChange"
          >
            <template #headerCell="{ title, column }">
              <template v-if="column.key === 'contactTel'">
                <span style="color: red">*</span><span> 手机号</span>
              </template>
              <template v-if="column.key === 'contactEmail'">
                <span style="color: red">*</span><span> 邮箱地址 </span>
              </template>
            </template>

            <template #bodyCell="{ text, record, index, column }">
              <template v-if="column.key === 'contactTel'">
                <span> {{ text ? text : "-" }}</span>
              </template>
              <template v-if="column.key === 'contactNoticeName'">
                <span v-if="text">{{ text }}</span>
                <a v-else href="#" @click.prevent="onAddContactClick(record)"
                  >新增</a
                >
              </template>
              <template v-if="column.key === 'contactEmail'">
                <span> {{ text ? text : "-" }}</span>
              </template>
              <template v-if="column.key === 'action'">
                <a
                  href=""
                  @click.prevent="editContact(record)"
                  v-if="record.contact_notice_id"
                  >编辑</a
                >
              </template>
            </template>
          </a-table>
        </a-form-item>
      </a-form>

      <div class="drawer-footer">
        <a-button class="mr-10" @click.prevent="closeDrawer">取消</a-button>
        <a-button type="primary" @click.prevent="onSubmit">生成缴费单</a-button>
      </div>
    </a-drawer>

    <add-contact
      @cancel="addContactClose"
      @ok="addContactSuccess"
      :visible="addContactVisible"
      :ownerName="addContactOwnerName"
      :ownerId="addContactOwnerId"
      :id="editContactId"
    ></add-contact>

    <a-modal
      v-model:visible="progressModalVisible"
      centered
      :footer="null"
      @ok="modal2Visible = false"
    >
      <h3>正在生成中</h3>
      <Progress :percent="progressPercent" style="margin-top: 20px" />
      <p v-if="progressPercent < 100" style="margin-top: 20px">
        正在自动生成中，请勿刷新或关闭本页面
      </p>
      <p v-else style="margin-top: 20px">已成功生成缴费通知单</p>
    </a-modal>
  </div>
</template>

<script>
import {
  defineComponent,
  ref,
  computed,
  watch,
  reactive,
  toRefs,
  toRaw,
  createVNode,
  h,
} from "vue";
import request from "../../../common/utils/request";
import { Form, message, Progress, notification, Modal } from "ant-design-vue";
import AddContact from "../AllBills/AddContact.vue";
import { ExclamationCircleOutlined } from "@ant-design/icons-vue";
const useForm = Form.useForm;
export default defineComponent({
  name: "ResendNotice",
  components: { Progress, AddContact },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    ids: {
      type: Array,
      default: () => [],
    },
    data: {
      type: Object,
      default: () => {},
    },
    noticeId: {
      type: [String, Number],
      default: 0,
    },
    taskKey: {
      type: String,
      default: "",
    },
  },
  setup(props, context) {
    const NoticeData = ref({});
    /**
     * @description: 表单字段
     */
    const modelRef = reactive({
      noticeType: [], //通知方式
      checkedNoticeList: [],
      receiverList: null,
    });

    /**
     * @description: 验证规则
     */
    const rulesRef = reactive({
      checkedNoticeList: [
        { required: true, message: "请至少选择一种通知方式" },
      ],
      receiverList: [{ required: true, message: "请完善通知联系人信息" }],
    });

    /**
     * @description: 创建表单
     */
    const { resetFields, validate, validateInfos } = useForm(
      modelRef,
      rulesRef
    );

    const state = reactive({
      indeterminate: false,
      noticeAll: false,

      noticeTypeList: [],

      selectedRowKeys: [],
      selectedRows: [],

      contactList: [], //通知单接收人table数据
    });

    watch(
      () => props.visible,
      (val) => {
        if (val) {
          console.log(props.data);
          NoticeData.value = props.data;
          getNoticeTypeList();
          getContactList();
          // 打开时初始化数据
          state.contactList = [];
          state.selectedRowKeys = [];
          state.selectedRows = [];
          init();
        } else {
          // 关闭时重置数据
          NoticeData.value = {};
          resetFields();
        }
      }
    );

    const getNoticeTypeList = () => {
      if (NoticeData.value.billIds && NoticeData.value.buildType) {
        request
          .post("/org", "/notice/buildInit", {
            billIds: NoticeData.value.billIds,
            build_type: NoticeData.value.buildType,
          })
          .then((res) => {
            state.noticeTypeList = res.initData?.noticeType;
          })
          .catch((err) => {
            console.log(err);
            if (err.code == 60024) {
              Modal.info({
                title: "提示",
                content: () => err.msg,
                centered: true,
                okText: () => "确定",
              });
            } else if (err.code == 60025) {
              Modal.confirm({
                title: "提示",
                content: () =>
                  h("div", { style: "color:#999;" }, [
                    h("p", {}, `以下楼宇未配置通知单打印模板：`),
                    h("p", { style: "font-size:16px;color:#333" }, err.msg),
                  ]),
                icon: () => createVNode(ExclamationCircleOutlined),
                centered: true,
                okText: () => "前往设置",
                onOk() {
                  context.emit("closeDrawer");
                  router.push({
                    name: "noticeSetting",
                    query: { type: "print" },
                  });
                },
                onCancel() {
                  context.emit("closeDrawer");
                },
              });
            } else if (err.code == 60026) {
              Modal.confirm({
                title: "提示",
                content: () =>
                  h("div", { style: "color:#999;" }, [
                    h("p", {}, `以下楼宇未配置通知单发送模板：`),
                    h("p", { style: "font-size:16px;color:#333" }, err.msg),
                  ]),
                icon: () => createVNode(ExclamationCircleOutlined),
                centered: true,
                okText: () => "前往设置",
                onOk() {
                  context.emit("closeDrawer");
                  router.push({
                    name: "noticeSetting",
                    query: { type: "send" },
                  });
                },
                onCancel() {
                  context.emit("closeDrawer");
                },
              });
            }
          });
      }
    };

    const onNoticeAllChange = (e) => {
      if (e.target.checked) {
        modelRef.checkedNoticeList = state.noticeTypeList.map((item) => {
          return item.key;
        });
        modelRef.checkedNoticeList = state.noticeTypeList.map((item) => {
          return item.key;
        });
        state.indeterminate = false;
        state.noticeAll = true;
      } else {
        modelRef.checkedNoticeList = [];
        state.indeterminate = false;
      }
    };

    watch(
      () => modelRef.checkedNoticeList,
      (val) => {
        state.indeterminate =
          !!val.length && val.length < state.noticeTypeList.length;
        state.noticeAll = val.length === state.noticeTypeList.length;
      }
    );

    /**
     * @description: 初始化
     */
    const init = () => {};

    const progressModalVisible = ref(false);
    const progressPercent = ref(0);

    const checkReceiver = () => {
      for (let item of state.contactList) {
        if (!item.contact_notice_id) {
          return null;
        }
      }
      return true;
    };

    let progressTimer = null;
    const progressTimerCount = ref(0); //定时器请求次数

    /**
     * @description: 提交表单
     */
    const onSubmit = () => {
      if (state.selectedRows.length == 0) {
        message.warning("请至少选择一个通知单接收人");
      } else {
        if (!modelRef.receiverList) {
          modelRef.receiverList = checkReceiver();
        }
        realSubmit();
      }
    };

    const realSubmit = () => {
      validate().then(() => {
        let submitParams = NoticeData.value;
        submitParams.noticeType = modelRef.checkedNoticeList;
        submitParams.noticeOwnerList = state.selectedRows;
        console.log(submitParams);

        request
          .post("/org", "/notice/resend", {
            buildData: { ...submitParams },
            noticeId: props.noticeId,
          })
          .then((res) => {
            // [1:下载打印； 2：短信通知； 3：邮件通知]
            if (modelRef.checkedNoticeList.includes(1)) {
              progressModalVisible.value = true;
              progressTimer = setInterval(() => {
                if (progressPercent.value >= 100) {
                  clearInterval(progressTimer);
                  message.success("生成成功");
                  setTimeout(() => {
                    progressModalVisible.value = false;
                    context.emit("success");
                  }, 1500);
                }
                if (progressTimerCount.value > 300) {
                  //定时器请求次数，当progressTimerCount>300（定时器五分钟）后，取消定时器，关闭进度条弹窗，提示失败,并清除taskKey
                  clearInterval(progressTimer);
                  notification.error({
                    description: "服务异常,请稍后重试",
                    onClick: () => {
                      console.log("Notification Clicked!");
                    },
                  });
                  setTimeout(() => {
                    progressModalVisible.value = false;
                  }, 1500);
                }
                progressTimerCount.value++;
                request
                  .get("/org", "/notice/downloadProgress", {
                    task_key: props.taskKey,
                    noticeId: props.noticeId,
                  })
                  .then((res) => {
                    if (
                      progressTimerCount.value > 120 &&
                      res.progressData.success == 0
                    ) {
                      //两分钟后，任无成功进程，取消定时器，关闭进度条弹窗，提示失败,并清除taskKey
                      clearInterval(progressTimer);
                      notification.error({
                        description: "服务异常,请稍后重试",
                        onClick: () => {
                          console.log("Notification Clicked!");
                        },
                      });
                      setTimeout(() => {
                        progressModalVisible.value = false;
                      }, 1500);
                    }
                    if (Number(res.progressData.taskCount) > 0) {
                      progressPercent.value =
                        (Number(res.progressData.success) /
                          Number(res.progressData.taskCount)) *
                        100;
                    }
                    if (res.progressData.zipFile.fileUrl) {
                      window.open(res.progressData.zipFile.fileUrl);
                    }
                    const percent = Math.round(progressPercent.value);
                    progressPercent.value = percent >= 100 ? 100 : percent;
                  });
              }, 1000);
            } else {
              message.success("生成成功");
              context.emit("success");
            }
          });
      });
    };

    const closeDrawer = () => {
      context.emit("closeDrawer");
    };

    const contactColumns = ref([
      {
        title: "租客名称",
        dataIndex: "name",
        width: "20%",
        ellipsis: true,
      },
      {
        title: "通知单联系人",
        dataIndex: "contact_notice_name",
        key: "contactNoticeName",
        width: "20%",
      },
      {
        dataIndex: "tel",
        key: "contactTel",
        width: "20%",
      },
      {
        dataIndex: "email",
        key: "contactEmail",
        width: "30%",
      },
      {
        title: "操作",
        dataIndex: "id",
        key: "action",
        width: "10%",
      },
    ]);

    const contactListLoading = ref(false);
    const page = ref(1);
    const limit = ref(10);
    const total = ref(0);
    const contactPagination = computed(() => ({
      total: total.value,
      current: page.value,
      pageSize: limit.value,
      showSizeChanger: true,
    }));

    const getContactList = () => {
      contactListLoading.value = true;
      request
        .post("/org", "/notice/getNoticeOwner", {
          billIds: NoticeData.value.billIds,
          build_type: NoticeData.value.buildType,
          page: page.value,
          limit: limit.value,
        })
        .then((res) => {
          state.contactList = res.list;
          contactListLoading.value = false;
        });
    };

    const handleTableChange = (pager, filters, sorter) => {
      page.value = pager.current;
      limit.value = pager.pageSize;
      getContactList();
    };

    const addContactVisible = ref(false);

    const addContactClose = () => {
      addContactVisible.value = false;
    };

    const addContactSuccess = () => {
      addContactClose();
      getContactList();
    };

    const addContactOwnerName = ref("");
    const addContactOwnerId = ref(0);
    const onAddContactClick = (record) => {
      addContactVisible.value = true;
      addContactOwnerName.value = record.name;
      addContactOwnerId.value = record.id;
    };

    const onSelectChange = (selectedRowKeys, selectedRows) => {
      console.log("selectedRowKeys changed: ", selectedRowKeys, selectedRows);
      state.selectedRowKeys = selectedRowKeys;
      state.selectedRows = selectedRows;
      if (selectedRows.length > 0) {
        modelRef.receiverList = checkReceiver();
      }
    };

    const editContactId = ref(null);

    const editContact = (record) => {
      addContactVisible.value = true;
      addContactOwnerName.value = record.name;
      editContactId.value = record.contact_notice_id;
    };

    watch(
      () => progressModalVisible.value,
      (val) => {
        console.log("progressModalVisible.value", progressModalVisible.value);
        if (val) {
          // 打开时初始化数据
        } else {
          // 关闭时重置数据
          progressTimerCount.value = 0;
          progressPercent.value = 0;
          clearInterval(progressTimer);
        }
      }
    );

    return {
      closeDrawer,
      onSubmit,
      modelRef,
      validateInfos,
      onNoticeAllChange,
      ...toRefs(state),

      contactPagination,

      addContactVisible,
      addContactClose,
      addContactSuccess,

      contactColumns,
      onAddContactClick,
      addContactOwnerName,
      addContactOwnerId,
      editContactId,

      contactListLoading,
      onSelectChange,
      progressModalVisible,
      progressPercent,
      editContact,
      handleTableChange,
    };
  },
});
</script>

<style lang="less" scoped>
#code-item {
  :deep(.ant-radio-button-wrapper) {
    padding-left: 25px;
    padding-right: 25px;
  }
}

:deep(.ant-card-body) {
  height: 130px;
}
</style>
